console.log('orders.js 已加载并执行。');
document.addEventListener('DOMContentLoaded', function() {
    // 获取 CSRF 令牌
    const csrfToken = document.querySelector('meta[name="_csrf"]').getAttribute('content');
    const csrfHeader = document.querySelector('meta[name="_csrf_header"]').getAttribute('content');

    // Status mapping for display
    const DISPLAY_STATUS_MAP = {
        "PENDING": "待处理",
        "SHIPPED": "已发货",
        "PICKED_UP": "已揽收",
        "IN_TRANSIT": "运输中",
        "UNRECEIVED": "未签收",
        "DELIVERED": "已签收",
        "CANCELED": "已取消"
    };

    // Helper function to get display status
    function getDisplayStatus(status) {
        return DISPLAY_STATUS_MAP[status] || status; // Return Chinese if mapped, else original
    }

    // Helper function to convert Chinese status back to English
    function getEnglishStatus(chineseStatus) {
        const reverseMap = {
            "待处理": "PENDING",
            "已发货": "SHIPPED", 
            "已揽收": "PICKED_UP",
            "运输中": "IN_TRANSIT",
            "未签收": "UNRECEIVED",
            "已签收": "DELIVERED",
            "已取消": "CANCELED"
        };
        return reverseMap[chineseStatus] || chineseStatus;
    }

    // Part 2: Modal logic
    document.querySelectorAll('.view-order-btn').forEach(button => {
        button.addEventListener('click', function(event) {
            event.preventDefault(); // Prevent default link behavior
            const orderId = this.dataset.orderId; // Get order ID from data attribute

            // Fetch order details from backend
            fetch(`/orders/${orderId}`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    return response.json();
                })
                .then(order => {
                    // Populate modal with order data
                    document.getElementById('modalOrderNumber').textContent = order.orderNumber;
                    document.getElementById('modalSenderName').textContent = order.senderName;
                    document.getElementById('modalSenderPhone').textContent = order.senderPhone;
                    document.getElementById('modalSenderAddress').textContent = order.senderAddress;
                    document.getElementById('modalReceiverName').textContent = order.receiverName;
                    document.getElementById('modalReceiverPhone').textContent = order.receiverPhone;
                    document.getElementById('modalReceiverAddress').textContent = order.receiverAddress;
                    document.getElementById('modalPackageType').textContent = order.packageType;
                    document.getElementById('modalWeight').textContent = order.weight;
                    document.getElementById('modalVolume').textContent = order.volume;
                    document.getElementById('modalPrice').textContent = order.price;
                    document.getElementById('modalStatus').textContent = getDisplayStatus(order.status); // Use translated status

                    // Format LocalDateTime for display
                    document.getElementById('modalCreatedAt').textContent = order.createdAt ? new Date(order.createdAt).toLocaleString() : '';
                    document.getElementById('modalUpdatedAt').textContent = order.updatedAt ? new Date(order.updatedAt).toLocaleString() : '';

                    // Show the modal
                    var myModal = new bootstrap.Modal(document.getElementById('orderDetailModal'));
                    myModal.show();
                })
                .catch(error => {
                    console.error('Error fetching order details:', error);
                    alert('无法加载订单详情，请稍后再试。');
                });
        });
    });

    // Part 3: Edit Order Modal Logic
    document.querySelectorAll('.edit-order-btn').forEach(button => {
        button.addEventListener('click', function(event) {
            event.preventDefault();
            const orderId = this.dataset.orderId;

            // Fetch order details to populate edit modal
            fetch(`/orders/${orderId}`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    return response.json();
                })
                .then(order => {
                    document.getElementById('editOrderId').value = order.id;
                    document.getElementById('editOrderNumber').value = order.orderNumber;
                    document.getElementById('editPackageType').value = order.packageType;
                    document.getElementById('editWeight').value = order.weight;
                    document.getElementById('editVolume').value = order.volume;
                    document.getElementById('editPrice').value = order.price;
                    // 将英文状态转换为中文来设置select值
                    document.getElementById('editStatus').value = getDisplayStatus(order.status);

                    var editModal = new bootstrap.Modal(document.getElementById('editOrderModal'));
                    editModal.show();
                })
                .catch(error => {
                    console.error('Error fetching order details for edit:', error);
                    alert('无法加载订单详情进行修改，请稍后再试。');
                });
        });
    });

    // Save changes to order
    const saveOrderChangesBtn = document.getElementById('saveOrderChangesBtn');
    if (saveOrderChangesBtn) {
        saveOrderChangesBtn.addEventListener('click', function() {
            const orderId = document.getElementById('editOrderId').value;
            const updatedOrder = {
                id: orderId,
                packageType: document.getElementById('editPackageType').value,
                weight: parseFloat(document.getElementById('editWeight').value),
                volume: parseFloat(document.getElementById('editVolume').value),
                price: parseFloat(document.getElementById('editPrice').value),
                status: getEnglishStatus(document.getElementById('editStatus').value) // 将中文状态转换为英文
            };

            fetch('/orders/update', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    [csrfHeader]: csrfToken
                },
                body: JSON.stringify(updatedOrder)
            })
            .then(response => {
                if (!response.ok) {
                    return response.json().then(errorData => {
                        throw new Error(errorData.message || '网络响应不正常');
                    });
                }
                return response.json();
            })
            .then(data => {
                if (data === true) {
                    alert('订单修改成功！');
                    location.reload();
                } else {
                    alert('订单修改失败！');
                }
            })
            .catch(error => {
                console.error('Error saving order changes:', error);
                alert('保存修改失败：' + error.message);
            });
        });
    }

    // Part 4: Cancel Order Modal Logic
    document.querySelectorAll('.cancel-order-btn').forEach(button => {
        button.addEventListener('click', function(event) {
            event.preventDefault();
            const orderId = this.dataset.orderId;
            document.getElementById('cancelOrderId').value = orderId;

            var cancelModal = new bootstrap.Modal(document.getElementById('cancelOrderConfirmModal'));
            cancelModal.show();
        });
    });

    // Confirm cancel order
    const confirmCancelOrderBtn = document.getElementById('confirmCancelOrderBtn');
    if (confirmCancelOrderBtn) {
        confirmCancelOrderBtn.addEventListener('click', function() {
            const orderId = document.getElementById('cancelOrderId').value;

            fetch(`/orders/admin/cancel/${orderId}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    [csrfHeader]: csrfToken
                }
            })
            .then(response => {
                if (!response.ok) {
                    return response.json().then(errorData => {
                        throw new Error(errorData.message || '网络响应不正常');
                    });
                }
                return response.json();
            })
            .then(data => {
                if (data === true) {
                    alert('订单取消成功！');
                    location.reload();
                } else {
                    alert('订单取消失败！');
                }
            })
            .catch(error => {
                console.error('Error canceling order:', error);
                alert('取消订单失败：' + error.message);
            });
        });
    }

    // Part 4: Delete Order Modal Logic
    document.querySelectorAll('.delete-order-btn').forEach(button => {
        button.addEventListener('click', function(event) {
            event.preventDefault();
            const orderId = this.dataset.orderId;
            document.getElementById('deleteOrderId').value = orderId;

            var deleteModal = new bootstrap.Modal(document.getElementById('deleteOrderConfirmModal'));
            deleteModal.show();
        });
    });

    // Confirm delete order
    const confirmDeleteOrderBtn = document.getElementById('confirmDeleteOrderBtn');
    if (confirmDeleteOrderBtn) {
        confirmDeleteOrderBtn.addEventListener('click', function() {
            const orderId = document.getElementById('deleteOrderId').value;

            fetch(`/orders/delete/${orderId}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    [csrfHeader]: csrfToken
                }
            })
            .then(response => {
                if (!response.ok) {
                    return response.json().then(errorData => {
                        throw new Error(errorData.message || '网络响应不正常');
                    });
                }
                return response.json(); // Assuming backend returns some success indicator
            })
            .then(data => {
                if (data === true) { // Assuming backend returns boolean true on success
                    alert('订单删除成功！');
                    location.reload(); // Reload page to reflect changes
                } else {
                    alert('订单删除失败！');
                }
            })
            .catch(error => {
                console.error('Error deleting order:', error);
                alert('删除订单失败：' + error.message);
            });
        });
    }
}); 